<script type="text/javascript">
    (function () {
        RED.nodes.registerType('ui-table', {
            category: RED._('@flowfuse/node-red-dashboard/ui-base:ui-base.label.category'),
            color: RED._('@flowfuse/node-red-dashboard/ui-base:ui-base.colors.medium'),
            defaults: {
                group: { type: 'ui-group', required: true },
                name: { value: '' },
                label: { value: 'text' },
                order: { value: 0 },
                width: {
                    value: 0,
                    validate: function (v) {
                        const width = v || 0
                        const currentGroup = $('#node-input-group').val() || this.group
                        const groupNode = RED.nodes.node(currentGroup)
                        const valid = !groupNode || +width <= +groupNode.width
                        $('#node-input-size').toggleClass('input-error', !valid)
                        return valid
                    }
                },
                height: { value: 0 },
                maxrows: { value: 0, validate: RED.validators.number() },
                passthru: { value: false },
                autocols: { value: true },
                showSearch: { value: true },
                selectionType: { value: 'none' },
                columns: {
                    value: null
                }
            },
            inputs: 1,
            outputs: 1,
            outputLabels: function () { return this.mode },
            icon: 'font-awesome/fa-table',
            paletteLabel: 'table',
            label: function () {
                return this.name || 'table'
            },
            oneditprepare: function () {
                // handle backward compatibility
                const validSelectionTypes = ['none', 'checkbox', 'click']
                if (!validSelectionTypes.includes(this.selectionType)) {
                    $('#node-input-selectionType').val('none')
                }
                // if this groups parent is a subflow template, set the node-config-input-width and node-config-input-height up
                // as typedInputs and hide the elementSizer (as it doesn't make sense for subflow templates)
                if (RED.nodes.subflow(this.z)) {
                    // change inputs from hidden to text & display them
                    $('#node-input-width').attr('type', 'text')
                    $('#node-input-height').attr('type', 'text')
                    $('div.form-row.nr-db-ui-element-sizer-row').hide()
                    $('div.form-row.nr-db-ui-manual-size-row').show()
                } else {
                    // not in a subflow, use the elementSizer
                    $('div.form-row.nr-db-ui-element-sizer-row').show()
                    $('div.form-row.nr-db-ui-manual-size-row').hide()
                    $('#node-input-size').elementSizer({
                        width: '#node-input-width',
                        height: '#node-input-height',
                        group: '#node-input-group'
                    })
                }
    
                const autocols = $('#node-input-autocols')

                $(autocols).change(() => {
                    const val = autocols.is(':checked')
                    const customColsDiv = $('#node-input-columns-container')
                    if (val) {
                        customColsDiv.hide()
                    } else {
                        customColsDiv.show()
                    }
                })

                // Columns Editor
                function generateColumn (i, col) {
                    const container = $('<li/>', { style: 'background: var(--red-ui-secondary-background, #fff); margin:0; padding:8px 0px 0px; border-bottom: 1px solid var(--red-ui-form-input-border-color, #ccc);' })
                    const row = $('<div/>').appendTo(container)
                    $('<div/>', { style: 'padding-top:5px; padding-left:175px;' }).appendTo(container)
                    $('<div/>', { style: 'padding-top:5px; padding-left:120px;' }).appendTo(container)

                    $('<i style="color: var(--red-ui-form-text-color, #eee); cursor:move; margin-left:3px;" class="node-input-column-handle fa fa-bars"></i>').appendTo(row)

                    $('<input/>', { class: 'node-input-column-key', type: 'text', style: 'margin-left:7px; width:calc(50% - 32px);', placeholder: RED._('@flowfuse/node-red-dashboard/ui-table:ui-table.label.key'), value: col.key }).appendTo(row)
                    $('<input/>', { class: 'node-input-column-label', type: 'text', style: 'margin-left:7px; width:calc(50% - 32px);', placeholder: RED._('@flowfuse/node-red-dashboard/ui-table:ui-table.label.label'), value: col.title }).appendTo(row)

                    const finalSpan = $('<span/>', { style: 'float:right; margin-right:8px;' }).appendTo(row)
                    const deleteButton = $('<a/>', { href: '#', class: 'editor-button editor-button-small', style: 'margin-top:7px; margin-left:5px;' }).appendTo(finalSpan)
                    $('<i/>', { class: 'fa fa-remove' }).appendTo(deleteButton)

                    deleteButton.click(function () {
                        container.css({ background: 'var(--red-ui-secondary-background-inactive, #fee)' })
                        container.fadeOut(300, function () {
                            $(this).remove()
                        })
                    })

                    $('#node-input-column-container').append(container)
                }

                $('#node-input-add-column').click(function () {
                    generateColumn($('#node-input-column-container').children().length + 1, {})
                    $('#node-input-column-container-div').scrollTop($('#node-input-column-container-div').get(0).scrollHeight)
                })

                for (let i = 0; i < this.columns?.length; i++) {
                    const col = this.columns[i]
                    generateColumn(i + 1, col)
                }

                $('#node-input-column-container').sortable({
                    axis: 'y',
                    handle: '.node-input-column-handle',
                    cursor: 'move'
                })
            },
            oneditsave: function () {
                const columns = $('#node-input-column-container').children()
                const node = this
                node.columns = []
                columns.each(function (i) {
                    const column = $(this)
                    const o = {
                        title: column.find('.node-input-column-label').val(),
                        key: column.find('.node-input-column-key').val()
                    }
                    node.columns.push(o)
                })
            }
        })
    })()
</script>

<script type="text/html" data-template-name="ui-table">
    <div class="form-row">
        <label for="node-input-name"><i class="fa fa-tag"></i> <span data-i18n="node-red:common.label.name"></label>
        <input type="text" id="node-input-name" data-i18n="[placeholder]node-red:common.label.name">
    </div>
    <div class="form-row">
        <label for="node-input-group"><i class="fa fa-table"></i> <span data-i18n="ui-table.label.group"></label>
        <input type="text" id="node-input-group">
    </div>
    <div class="form-row nr-db-ui-element-sizer-row">
        <label><i class="fa fa-object-group"></i> <span data-i18n="ui-table.label.size">Size</label>
        <button class="editor-button" id="node-input-size"></button>
    </div>
    <div class="form-row nr-db-ui-manual-size-row">
        <label><i class="fa fa-arrows-h"></i> <span data-i18n="ui-table.label.width">Width</label>
        <input type="hidden" id="node-input-width">
    </div>
    <div class="form-row nr-db-ui-manual-size-row">
        <label><i class="fa fa-arrows-v"></i> <span data-i18n="ui-table.label.height">Height</label>
        <input type="hidden" id="node-input-height">
    </div>
    <div class="form-row">
        <label for="node-input-maxrows"><i class="fa fa-tag"></i> <span data-i18n="ui-table.label.maxRows"></label>
        <input type="number" id="node-input-maxrows">
    </div>
    <div class="form-row">
        <label for="node-input-selectionType"><i class="fa fa-crosshairs"></i> <span data-i18n="ui-table.label.selection"></span></label>
        <select id="node-input-selectionType">
            <option value="none" data-i18n="ui-table.selection.none"></option>
            <option value="click" data-i18n="ui-table.selection.click"></option>
            <option value="checkbox" data-i18n="ui-table.selection.checkbox"></option>
        </select>
    </div>
    <div class="form-row form-row-flex">
        <label for="node-input-showSearch"><i class="fa fa-search"></i> <span data-i18n="ui-table.label.search"></label>
        <div style="margin-bottom: 0px; width:calc(70% + 15px);">
            <input type="checkbox" id="node-input-showSearch" style="display: inline-block; width: auto;">
            <label  for="node-input-showSearch" data-i18n="ui-table.label.showSearch"></label>
        </div>
    </div>
    <div class="form-row" style="display:flex;">
        <label for="node-input-width" style="vertical-align:top"><i class="fa fa-list-alt"></i> <span data-i18n="ui-table.label.columns"></label>
        <div class="form-row node-input-column-container-row" style="margin-bottom: 0px; width:calc(70% + 15px);">
            <div>
                <input type="checkbox" checked id="node-input-autocols" style="display: inline-block; width: auto; margin: 0px 0px 0px 4px;">
                <label style="width:auto" for="node-input-autocols" data-i18n="ui-table.label.autoCalculateColumns"></label>
            </div>
            <div id="node-input-columns-container">
                <div id="node-input-column-container-div" style="box-sizing:border-box; border-radius:5px; height:257px; padding:5px; border:1px solid var(--red-ui-form-input-border-color, #ccc); overflow-y:scroll; display:inline-block; width: 100%;">
                    <ol id="node-input-column-container" style="list-style-type:none; margin:0;"></ol>
                </div>
                <a href="#" class="editor-button editor-button-small" id="node-input-add-column" style="margin-top:4px;"><i class="fa fa-plus"></i> <span data-i18n="ui-table.label.columns"></span></a>
            </div>
        </div>
    </div>
</script>
